/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.modules.storage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * Uses {@link InputStream} as a source to read the data from.
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * @param <T>
 *            data type
 */
public abstract class AbstractStreamReader<T> extends
		AbstractReader<T, InputStream> {

	private final File file;
	private InputStream inputStream;
	private final boolean closeAfterRead;

	/**
	 * Constructs a new {@link AbstractStreamReader} that uses the specified
	 * {@link File} for the future reading.
	 * 
	 * @param file
	 *            the file to read a data from
	 */
	public AbstractStreamReader(File file) {
		if (file == null) {
			throw new IllegalArgumentException("file cannot be null");
		}
		this.file = file;
		closeAfterRead = true;
	}

	/**
	 * Constructs a new {@link AbstractStreamReader} that uses a {@link File}
	 * created by converting the specified path string.
	 * 
	 * @param path
	 *            the path of a file to read a data from
	 */
	public AbstractStreamReader(String path) {
		this(new File(path));
	}

	/**
	 * Constructs a new {@link AbstractStreamReader} that uses the specified
	 * {@link InputStream} for the future reading.
	 * 
	 * @param inputStream
	 *            the stream to read a data from
	 * @param closeAfterRead
	 *            defines whether to close the stream after {@link #read()}
	 *            completes
	 */
	public AbstractStreamReader(InputStream inputStream, boolean closeAfterRead) {
		if (inputStream == null) {
			throw new IllegalArgumentException("inputStream cannot be null");
		}
		this.inputStream = inputStream;
		this.closeAfterRead = closeAfterRead;
		file = null;
	}

	@Override
	public final void closeIO(InputStream io) throws IOException {
		io.close();
	}

	@Override
	public final InputStream openIO() throws IOException {
		if (file != null) {
			inputStream = new FileInputStream(file);
		}
		return inputStream;
	}

	@Override
	public final boolean shouldCloseIOAfterComplete() {
		return closeAfterRead;
	}

}
